<template>
  <div class="medical-order-detail">
    <!-- 页面头部 -->
         <div class="page-header">
       <h2>订单详情-{{ orderDetail?.orderInfo?.statusText }}</h2>
       <div class="header-actions">
         <button 
           v-if="orderDetail?.orderInfo?.status === 0" 
           @click="showShipDialog = true" 
           class="action-button ship"
         >
           订单发货
         </button>
         <button 
           v-if="orderDetail?.orderInfo?.status === 1" 
           @click="confirmReceipt" 
           class="action-button confirm"
         >
           确认收货
         </button>
         <button @click="goBack" class="action-button back">
           返回
         </button>
       </div>
     </div>

         <!-- 订单信息 -->
     <div class="info-section">
       <h3>订单信息</h3>
       <div class="info-grid">
         <div class="info-item">
           <label>订单编号：</label>
           <span>{{ orderDetail?.orderInfo?.orderNo }}</span>
         </div>
         <div class="info-item">
           <label>订单金额：</label>
           <span>¥{{ orderDetail?.orderInfo?.totalAmount }}</span>
         </div>
         <div class="info-item">
           <label>状态：</label>
           <span :class="['status-badge', getStatusClass(orderDetail?.orderInfo?.status)]">
             {{ orderDetail?.orderInfo?.statusText }}
           </span>
         </div>
         <div class="info-item">
           <label>提交时间：</label>
           <span>{{ formatDateTime(orderDetail?.orderInfo?.createdAt) }}</span>
         </div>
       </div>
     </div>

         <!-- 货物信息 -->
     <div class="info-section">
       <h3>货物信息</h3>
       <div class="goods-list">
         <div v-if="loading" class="loading">加载中...</div>
         <div v-else-if="!orderDetail?.orderItems || orderDetail.orderItems.length === 0" class="empty">
           暂无货物信息
         </div>
         <div v-else v-for="item in orderDetail.orderItems" :key="item.id" class="goods-item">
                       <div class="goods-image">
              <div class="placeholder-image">
                <span>药品</span>
              </div>
            </div>
           <div class="goods-info">
             <h4>{{ item.medicineName }}</h4>
             <p class="quantity">x{{ item.quantity }}</p>
             <p class="specification">规格：{{ item.specification }}</p>
             <p class="price">单价：¥{{ item.unitPrice }}</p>
             <p class="subtotal">小计：¥{{ item.subtotal }}</p>
           </div>
         </div>
       </div>
     </div>

         <!-- 收货人信息 -->
     <div class="info-section">
       <h3>收货人信息</h3>
       <div class="info-grid">
         <div class="info-item">
           <label>收货人：</label>
           <span>{{ extractRecipientFromAddress(orderDetail?.orderInfo?.deliveryAddress) }}</span>
         </div>
         <div class="info-item">
           <label>电话：</label>
           <span>{{ orderDetail?.orderInfo?.username }}</span>
         </div>
         <div class="info-item full-width">
           <label>收货地址：</label>
           <span>{{ orderDetail?.orderInfo?.deliveryAddress }}</span>
         </div>
       </div>
     </div>

     <!-- 物流信息 -->
     <div v-if="orderDetail?.orderInfo?.status >= 1" class="info-section">
       <h3>物流信息</h3>
       <div class="info-grid">
         <div class="info-item">
           <label>物流公司：</label>
           <span>{{ orderDetail?.orderInfo?.logisticsCompany || '-' }}</span>
         </div>
         <div class="info-item">
           <label>物流单号：</label>
           <span>{{ orderDetail?.orderInfo?.trackingNumber || '-' }}</span>
         </div>
         <div class="info-item">
           <label>操作：</label>
           <button 
             v-if="orderDetail?.orderInfo?.trackingNumber" 
             @click="viewLogistics" 
             class="action-button logistics"
           >
             查看物流
           </button>
         </div>
       </div>
     </div>

    <!-- 发货对话框 -->
    <div v-if="showShipDialog" class="modal-overlay" @click="closeShipDialog">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>发货</h3>
          <button @click="closeShipDialog" class="close-button">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>配送方式：</label>
            <select v-model="shipForm.logisticsCompany" class="form-select">
              <option value="">请选择物流公司</option>
              <option v-for="company in logisticsCompanies" :key="company.code" :value="company.code">
                {{ company.name }}
              </option>
            </select>
          </div>
          <div class="form-group">
            <label>物流单号：</label>
            <input 
              v-model="shipForm.trackingNumber" 
              type="text" 
              placeholder="请输入物流单号"
              class="form-input"
            />
          </div>
        </div>
        <div class="modal-footer">
                   <button @click="submitShipOrder" class="confirm-button" :disabled="!canSubmitShip">
           确定
         </button>
          <button @click="closeShipDialog" class="cancel-button">
            取消
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import api from '../utils/request';

const router = useRouter();
const route = useRoute();

// 响应式数据
const loading = ref(false);
const orderDetail = ref<any>(null);
const showShipDialog = ref(false);
const logisticsCompanies = ref<any[]>([]);

// 发货表单
const shipForm = reactive({
  logisticsCompany: '',
  trackingNumber: ''
});

// 计算属性
const canSubmitShip = computed(() => {
  return shipForm.logisticsCompany && shipForm.trackingNumber.trim();
});

// 获取订单详情
const loadOrderDetail = async () => {
  try {
    loading.value = true;
    const orderId = Number(route.params.id);
    const response = await api.medicalOrder.getDetail(orderId);
    
    if (response && response.data) {
      orderDetail.value = response.data;
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    alert('获取订单详情失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 获取物流公司列表
const loadLogisticsCompanies = async () => {
  try {
    const response = await api.medicalOrder.getLogisticsCompanies();
    if (response && response.data) {
      logisticsCompanies.value = response.data;
    }
  } catch (error) {
    console.error('获取物流公司列表失败:', error);
  }
};

// 提交发货
const submitShipOrder = async () => {
  try {
    const orderId = Number(route.params.id);
    const data = {
      orderId: orderId,
      logisticsCompany: shipForm.logisticsCompany, // 这里发送的是物流公司代码
      trackingNumber: shipForm.trackingNumber.trim()
    };
    
    const response = await api.medicalOrder.shipOrder(data);
    
    if (response && response.data) {
      alert('订单发货成功！');
      closeShipDialog();
      // 重新加载订单详情
      await loadOrderDetail();
      // 返回列表页面并刷新
      router.push('/drug-order-management?refresh=true');
    }
  } catch (error) {
    console.error('订单发货失败:', error);
    alert('订单发货失败，请重试');
  }
};

// 确认收货
const confirmReceipt = async () => {
  try {
    if (confirm('确认要收货吗？')) {
      const orderId = Number(route.params.id);
      const data = { orderId: orderId };
      
      const response = await api.medicalOrder.confirmReceipt(data);
      
      if (response && response.data) {
        alert('确认收货成功！');
        // 重新加载订单详情
        await loadOrderDetail();
        // 返回列表页面并刷新
        router.push('/drug-order-management?refresh=true');
      }
    }
  } catch (error) {
    console.error('确认收货失败:', error);
    alert('确认收货失败，请重试');
  }
};

// 查看物流
const viewLogistics = async () => {
  try {
    const orderId = Number(route.params.id);
    const response = await api.medicalOrder.getLogisticsTracking(orderId);
    
    if (response && response.data) {
      const tracking = response.data;
      let trackingInfo = `物流追踪信息：\n\n物流公司：${tracking.logisticsCompany}\n物流单号：${tracking.trackingNumber}\n订单编号：${tracking.orderNo}\n\n追踪记录：\n`;
      
      if (tracking.trackingRecords && tracking.trackingRecords.length > 0) {
        tracking.trackingRecords.forEach((record: any, index: number) => {
          const time = new Date(record.time).toLocaleString('zh-CN');
          trackingInfo += `${index + 1}. ${time}\n   状态：${record.status}\n   位置：${record.location}\n\n`;
        });
      } else {
        trackingInfo += '暂无追踪记录';
      }
      
      alert(trackingInfo);
    }
  } catch (error) {
    console.error('获取物流追踪信息失败:', error);
    alert('获取物流追踪信息失败，请重试');
  }
};

// 关闭发货对话框
const closeShipDialog = () => {
  showShipDialog.value = false;
  shipForm.logisticsCompany = '';
  shipForm.trackingNumber = '';
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 格式化日期时间
const formatDateTime = (dateTime: string | Date) => {
  if (!dateTime) return '-';
  const date = new Date(dateTime);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '待发货';
    case 1: return '待收货';
    case 2: return '已收货';
    case 6: return '已取消';
    default: return '未知状态';
  }
};

// 获取状态样式类
const getStatusClass = (status: number) => {
  switch (status) {
    case 0: return 'status-pending';
    case 1: return 'status-shipping';
    case 2: return 'status-received';
    case 6: return 'status-cancelled';
    default: return 'status-unknown';
  }
};

 // 从地址中提取收货人信息
 const extractRecipientFromAddress = (address: string) => {
   if (!address) return '-';
   // 简单的提取逻辑，假设地址格式为 "收货人姓名, 详细地址"
   const parts = address.split(',');
   return parts[0] || '-';
 };

// 生命周期钩子
onMounted(async () => {
  await Promise.all([
    loadOrderDetail(),
    loadLogisticsCompanies()
  ]);
});
</script>

<style scoped>
.medical-order-detail {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.action-button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.action-button.ship {
  background-color: #52c41a;
  color: white;
}

.action-button.ship:hover {
  background-color: #73d13d;
}

.action-button.back {
  background-color: #1890ff;
  color: white;
}

.action-button.back:hover {
  background-color: #40a9ff;
}

.action-button.confirm {
  background-color: #fa8c16;
  color: white;
}

.action-button.confirm:hover {
  background-color: #ffa940;
}

.action-button.logistics {
  background-color: #722ed1;
  color: white;
  padding: 4px 12px;
  font-size: 12px;
}

.action-button.logistics:hover {
  background-color: #9254de;
}

.info-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.info-section h3 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.info-item label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
}

.info-item span {
  color: #333;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.pending-payment {
  background-color: #fff7e6;
  color: #fa8c16;
}

.status-badge.paid {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status-badge.reviewed {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-badge.pending-shipment {
  background-color: #fff2e8;
  color: #fa541c;
}

.status-badge.shipped {
  background-color: #f0f5ff;
  color: #722ed1;
}

.status-badge.received {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-badge.cancelled {
  background-color: #fff1f0;
  color: #f5222d;
}

.status-badge.unknown {
  background-color: #f5f5f5;
  color: #999;
}

.goods-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.goods-item {
  display: flex;
  gap: 16px;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.goods-image {
  width: 80px;
  height: 80px;
  flex-shrink: 0;
}

 .goods-image img {
   width: 100%;
   height: 100%;
   object-fit: cover;
   border-radius: 4px;
 }

 .placeholder-image {
   width: 100%;
   height: 100%;
   background-color: #f0f0f0;
   border-radius: 4px;
   display: flex;
   align-items: center;
   justify-content: center;
   color: #999;
   font-size: 12px;
   font-weight: 500;
 }

.goods-info {
  flex: 1;
}

.goods-info h4 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 16px;
}

.goods-info p {
  margin: 4px 0;
  color: #666;
  font-size: 14px;
}

 .goods-info .quantity {
   color: #1890ff;
   font-weight: 500;
 }

 .goods-info .price {
   color: #666;
   font-size: 13px;
 }

 .goods-info .subtotal {
   color: #fa8c16;
   font-weight: 500;
   font-size: 14px;
 }

.loading, .empty {
  text-align: center;
  padding: 40px;
  color: #999;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-button:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-select, .form-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-select:focus, .form-input:focus {
  outline: none;
  border-color: #1890ff;
}

.modal-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
}

.confirm-button, .cancel-button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.confirm-button {
  background-color: #1890ff;
  color: white;
}

.confirm-button:hover:not(:disabled) {
  background-color: #40a9ff;
}

.confirm-button:disabled {
  background-color: #f5f5f5;
  color: #d9d9d9;
  cursor: not-allowed;
}

.cancel-button {
  background-color: white;
  color: #666;
  border: 1px solid #ddd;
}

.cancel-button:hover {
  border-color: #1890ff;
  color: #1890ff;
}

/* 状态标签样式 */
.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-pending {
  background-color: #fff7e6;
  color: #fa8c16;
}

.status-shipping {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status-received {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-cancelled {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.status-unknown {
  background-color: #f5f5f5;
  color: #999;
}
</style> 